package org.fuys.coder.infrastructure.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.fuys.coder.domain.file.repository.IFileRepository;
import org.fuys.coder.infrastructure.dao.FileMapper;
import org.fuys.coder.infrastructure.model.po.File;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @projectName: fuys-low-coder
 * @package: org.fuys.coder.infrastructure.repository
 * @className: FileRepository
 * @author: WangJing
 * @description: 文件仓储实现
 * @date: 2024/6/28 23:02
 * @version: 1.0
 */
@Service
public class FileRepository implements IFileRepository {

    @Resource
    private FileMapper fileMapper;

    @Override
    public int save(String fileName, String type,Integer userId) {
        final File file = new File();
        file.setUserId(userId);
        file.setName(fileName);
        file.setType(type);
        fileMapper.insert(file);
        return file.getId();
    }

    @Override
    public String getFileKey(Long id) {
        final File file = fileMapper.selectOne(new LambdaQueryWrapper<File>().select(File::getName)
                .eq(File::getId, id));
        if(ObjectUtils.isEmpty(file)){
            return null;
        }
        return file.getName();
    }

    @Override
    public List<String> getFileKeys(List<Long> ids) {
        final List<File> files = fileMapper.selectList(new LambdaQueryWrapper<File>().select(File::getName)
                .in(File::getId, ids));
        if(ObjectUtils.isEmpty(files)){
            return null;
        }
        return files.stream().map(File::getName).collect(Collectors.toList());
    }

    @Override
    public Integer getFileId(String fileKey) {
        final File file = fileMapper.selectOne(new LambdaQueryWrapper<File>()
                .select(File::getId).eq(File::getName, fileKey));
        if(file==null){
            return null;
        }
        return file.getId();
    }
}
